﻿Imports CupsApp.Service
Partial Public Class users
    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CType(Master.FindControl("lnkAdmin"), LinkButton).Enabled = False
        CType(Master.FindControl("lnkAdmin"), LinkButton).Text = "> Administrator <"

    End Sub

    Protected Sub lnkReports_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lnkReports.Click
        Response.Redirect("select_reports.aspx")
    End Sub


    Protected Sub btnCreateUser_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCreateUser.Click
        Dim context As New HttpContextWrapper(HttpContext.Current)
        Dim service As CupsDomainService = DomainServicesFactory.CreateDomainService(context)
        If (Page.IsValid) Then
            If (service.CreateUser(txtUsername.Text, txtPassword.Text)) Then
                lvlMsg.Text = "User Saved"
            Else
                lvlMsg.Text = "User Not Saved"
            End If
            Page.DataBind()
        End If
    End Sub

    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        Dim context As New HttpContextWrapper(HttpContext.Current)
        Dim service As CupsDomainService = DomainServicesFactory.CreateDomainService(context)

        If (e.CommandName = "Unlock") Then
            If (service.UnlockUser(e.CommandArgument)) Then
                lvlMsg.Text = String.Format("User: {0} unlocked", e.CommandArgument)
            Else
                lvlMsg.Text = String.Format("Failed to inlock User : {0}", e.CommandArgument)
            End If
        ElseIf (e.CommandName = "Reset Password") Then
            Dim newPassword As String = service.ResetPassword(e.CommandArgument)
            If (Not String.IsNullOrEmpty(newPassword)) Then
                lvlMsg.Text = String.Format("User: {0} Password changed to {1}", e.CommandArgument, newPassword)
            Else
                lvlMsg.Text = "Can not reset password"
            End If
            lvlMsg.Visible = True


        ElseIf (e.CommandName = "Make Admin") Then
            Try
                Roles.AddUserToRole(e.CommandArgument, "Administrator")
                lvlMsg.Text = String.Format("User: {0} added as administrator", e.CommandArgument)
            Catch ex As Exception
                lvlMsg.Text = String.Format("Unable to add User {0} as administrator", e.CommandArgument)
            End Try

        End If
    End Sub
End Class